<template>
    <div class="loginBody">
        <div class="loginDiv">
            <div class="login-content">
                <h1 class="login-title">用户登录</h1>
                <el-form :model="loginForm" label-width="100px"
                         :rules="rules" ref="loginForm">
                    <el-form-item label="账号" prop="account">
                        <el-input style="width: 200px" type="text" v-model="loginForm.account"
                                  autocomplete="off" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input style="width: 200px" type="password" v-model="loginForm.password"
                                  show-password autocomplete="off" size="small" @keyup.enter.native="confirm"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="confirm" :disabled="confirm_disabled" size="medium" >确      定</el-button>
                        <el-button type="primary" @click="add" size="medium">注      册</el-button>
                    </el-form-item>
                </el-form>
              <el-dialog
                  title="注册"
                  :visible.sync="centerDialogVisible"
                  width="30%"
                  center>

                <el-form ref="registerForm" :rules="registerRules" :model="registerForm" label-width="80px">
                  <el-form-item label="账号" prop="account">
                    <el-col :span="20">
                      <el-input v-model="registerForm.account"></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="用户名" prop="userName">
                    <el-col :span="20">
                      <el-input v-model="registerForm.userName"></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="密码" prop="password">
                    <el-col :span="20">
                      <el-input v-model="registerForm.password"
                                show-password="off" size="small"></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="性别">
                    <el-radio-group v-model="registerForm.gender">
                      <el-radio label="1">男</el-radio>
                      <el-radio label="0">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="电话" prop="phone">
                    <el-col :span="20">
                      <el-input v-model="registerForm.phone"></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-col :span="20">
                      <el-input v-model="registerForm.email"></el-input>
                    </el-col>
                  </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="centerDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="register">确 定</el-button>
                </span>
              </el-dialog>
            </div>
        </div>
    </div>
</template>


<script>
    export default {
        name: "Login",
        data(){
            let checkDuplicate =(rule,value,callback)=>{
              if(this.registerForm.id){
                return callback();
              }
              this.$axios.get(this.$httpUrl+"/sns-user/findByAccount?account="+this.registerForm.account).then(res=>res.data).then(res=>{
                if(res.code!=200){

                  callback()
                }else{
                  callback(new Error('账号已经存在'));
                }
              })
            };
            return{
                times:'',
                centerDialogVisible:false,
                confirm_disabled:false,
                loginForm:{
                    account:'',
                    password:''
                },
                form:{
                  id:'',
                  lastTime:'',
                },
                registerForm:{
                  id:'',
                  account:'',
                  userName:'',
                  password:'',
                  gender:'1',
                  phone:'',
                  email:'',
                  roleId:'2',
                  permission:'1',
                  registerTime:''
                },
                rules:{
                    account: [
                        { required: true, message: '请输入账号', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输密码', trigger: 'blur' }
                    ],
                },
                registerRules: {
                  account: [
                    {required: true, message: '请输入账号', trigger: 'blur'},
                    {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'},
                    {validator:checkDuplicate,trigger: 'blur'}
                  ],
                  userName: [
                    {required: true, message: '请输入用户名', trigger: 'blur'}
                  ],
                  password: [
                    { required: true, message: '请输密码', trigger: 'blur' }
                  ],
                  phone: [
                    {required: true,message: "手机号不能为空",trigger: "blur"},
                    {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
                  ]
                }
            }
        },
        created() {
          this.getTimes()
        },
        methods:{
            resetForm() {
              this.$refs.registerForm.resetFields();
            },
            confirm(){
                this.confirm_disabled=true;
                this.$refs.loginForm.validate((valid) => {
                    if (valid) { //valid成功为true，失败为false
                        //去后台验证用户名密码
                        this.$axios.post(this.$httpUrl+'/sns-user/login',this.loginForm).then(res=>res.data).then(res=>{
                            console.log(res)
                            if(res.code==200){
                                //存储
                                sessionStorage.setItem("CurUser",JSON.stringify(res.data.user))
                                sessionStorage.setItem("isLogin",1)
                                console.log(res.data.menu)
                                this.$store.commit("setMenu",res.data.menu)
                                this.$store.commit("setMenu2",res.data.menu2)
                                this.form.id = res.data.user.id
                                this.form.lastTime = this.times
                                this.updateLastTime()
                                //跳转到主页
                                this.$router.replace('/Index');
                            }else if(res.code == 401){
                                this.confirm_disabled=false;
                                // alert('没有登录权限，请联系管理员！');
                                this.$message({
                                  message: '没有登录权限，请联系管理员！',
                                  type: 'warning'
                                });
                                return false;
                            }else{
                                this.confirm_disabled=false;
                                // alert('用户名或密码错误！');
                                this.$message({
                                  message: '用户名或密码错误！',
                                  type: 'warning'
                                });
                                return false;
                            }
                        });
                    } else {
                        this.confirm_disabled=false;
                        console.log('校验失败');
                        return false;
                    }
                });

            },
            add(){

              this.centerDialogVisible = true
              this.$nextTick(()=>{
                this.resetForm()
              })
            },
            register(){
              this.registerForm.registerTime = this.times
              this.$axios.post(this.$httpUrl+'/sns-user/save',this.registerForm).then(res=>res.data).then(res=>{
                console.log(res)
                if(res.code==200){

                  this.$message({
                    message: '注册成功！',
                    type: 'success'
                  });
                  this.centerDialogVisible = false
                  this. resetForm()
                }else{
                  this.$message({
                    message: '服务器异常！',
                    type: 'error'
                  });
                }

              })
            },
            updateLastTime(){
              this.$axios.post(this.$httpUrl+'/sns-user/update',this.form).then(res=>res.data)
            },
            getTimes(){
              setInterval(this.getTimesInterval, 1000);
            },
            getTimesInterval:function() {
              const newtime = new Date();
              let year = this.getIncrease(newtime.getFullYear(),4); //获取当前时间的年份
              let month = this.getIncrease(newtime.getMonth() + 1,2); //获取当前时间的月份
              let day = this.getIncrease(newtime.getDate(),2); //获取当前时间的天数
              let hours = this.getIncrease(newtime.getHours(),2); //获取当前时间的小时
              let minutes = this.getIncrease(newtime.getMinutes(),2); //获取当前时间的分数
              let seconds = this.getIncrease(newtime.getSeconds(),2); //获取当前时间的秒数
              //拼接格式化当前时间
              this.times = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
            },
            getIncrease(num, digit) {
              var increase = "";
              for (var i = 0; i < digit; i++) {
                increase += "0";
              }
              return (increase + num).slice(-digit);
            }
        }
    }
</script>

<style scoped>
    .loginBody {
        position: absolute;
        width: 100%;
        height: 100%;
        background-color: #B3C0D1;
    }
    .loginDiv {
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -200px;
        margin-left: -250px;
        width: 450px;
        height: 330px;
        background: #fff;
        border-radius: 5%;

    }
    .login-title {
        margin: 20px 0;
        text-align: center;
    }
    .login-content {
        width: 400px;
        height: 250px;
        position: absolute;
        top: 25px;
        left: 25px;
    }
</style>